package com.genesis.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.genesis.mall.common.CustomException;
import com.genesis.mall.common.Result;
import com.genesis.mall.config.RedisCache;
import com.genesis.mall.dto.InfoDto;
import com.genesis.mall.entity.*;
import com.genesis.mall.service.*;
import com.genesis.mall.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-08-01
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class UmsAdminController {

    @Autowired
    private IUmsAdminService adminService;

    @Autowired
    private IUmsAdminRoleRelationService adminRoleRelationService;

    @Autowired
    private IUmsRoleService roleService;

    @Autowired
    private IUmsRoleMenuRelationService roleMenuRelationService;

    @Autowired
    private IUmsMenuService menuService;

    @Autowired
    private RedisCache redisCache;

    @PostMapping("/login")
    public Result<Map> login(@RequestBody Map map, HttpServletRequest request){
        log.info("map",map);
        String username = (String) map.get("username");

        String pass = (String) map.get("password");

        //加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(pass);
        //查询数据库
        LambdaQueryWrapper<UmsAdmin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UmsAdmin::getUsername,username);
        wrapper.eq(UmsAdmin::getStatus,1);
        UmsAdmin umsAdmin = adminService.getOne(wrapper);

        if (umsAdmin==null){
             throw new CustomException("用户名错误");
        }
        if (umsAdmin.getStatus()==0){
             throw new CustomException("用户已禁用");
        }
        //判断用户密码
        if (umsAdmin.getPassword().equals(password)){
            throw new CustomException("密码错误");
        }
        Map<String, String> hashMap = new HashMap<>();
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("userId",umsAdmin.getId().toString());

        String token = TokenUtil.getToken(tokenMap);

       // redisCache.setCacheObject("token",token);

        hashMap.put("token",token);
        hashMap.put("tokenHead","Bearer ");


        return Result.success(hashMap);

    }

      @GetMapping("/info")
      public Result<InfoDto>info(HttpServletRequest request,@RequestHeader(HttpHeaders.AUTHORIZATION) String authorisation){
        log.info("src/test",authorisation);
         Enumeration<String> authorization= request.getHeaders("Authorization");
         String token=authorisation.substring(6);
         // String token = redisCache.getCacheObject("token");

          //String token = request.getHeader("token");
      /*    boolean flag = TokenUtil.verifyToken(authorisation);
          if (!flag) {
              throw new CustomException("token已失效");
          }*/
          Claims claims = TokenUtil.getClaims(token);
          String id = (String) claims.get("userId");
          UmsAdmin umsAdmin = adminService.getById(id);

          InfoDto infoDto = new InfoDto();
          infoDto.setIcon(umsAdmin.getIcon());
          infoDto.setUsername(umsAdmin.getUsername());

          LambdaQueryWrapper<UmsAdminRoleRelation> queryWrapper = new LambdaQueryWrapper<>();
          queryWrapper.eq(UmsAdminRoleRelation::getAdminId,umsAdmin.getId());
          UmsAdminRoleRelation roleRelation = adminRoleRelationService.getOne(queryWrapper);

          LambdaQueryWrapper<UmsRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
          roleLambdaQueryWrapper.eq(UmsRole::getId,roleRelation.getRoleId());
          UmsRole role = roleService.getOne(roleLambdaQueryWrapper);
          List<String> roles = new ArrayList<>();
          roles.add(role.getName());
          infoDto.setRoles(roles);

          LambdaQueryWrapper<UmsRoleMenuRelation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
          lambdaQueryWrapper.eq(UmsRoleMenuRelation::getRoleId,roleRelation.getRoleId());
          List<UmsRoleMenuRelation> list = roleMenuRelationService.list(lambdaQueryWrapper);
          List<UmsMenu> umsMenus = new ArrayList<>();
          for (UmsRoleMenuRelation roleMenuRelation : list) {
              UmsMenu umsMenu = new UmsMenu();
              LambdaQueryWrapper<UmsMenu> umsMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
              umsMenuLambdaQueryWrapper.eq(UmsMenu::getId,roleMenuRelation.getMenuId());
              UmsMenu menu=  menuService.getOne(umsMenuLambdaQueryWrapper);
              umsMenus.add(menu);
          }
          infoDto.setMenus(umsMenus);


          return Result.success(infoDto);
      }

      @PostMapping("/logout")
      public Result<String>logout(HttpServletRequest request,@RequestHeader(HttpHeaders.AUTHORIZATION) String authorisation){
          redisCache.deleteObject("token");

          return Result.success("退出成功");


      }
}
